package com.zhenyi.liuxue.index;

import java.util.ArrayList;
import java.util.List;

import com.cjw.model.DBMap;
import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.Kv;
import com.jfinal.kit.LogKit;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import com.jfinal.plugin.ehcache.CacheInterceptor;
import com.jfinal.plugin.ehcache.CacheName;
import com.liuxue.common.model.LxCnSchool;
import com.liuxue.common.model.LxSchoolRank;
import com.liuxue.common.model.LxStatistic;
import com.liuxue.common.model.LxUkSchool;
import com.utils.interceptor.TestInterceptor;
import com.zhenyi.liuxue.core.UpdateUtils;

/**
 * 搜索大学标准
 * 
 * @author cen
 *
 */
public class SearchController extends LXController {

	@Clear
	@Before(TestInterceptor.class)
	public void updatecertcontent() {
		UpdateUtils utils = new UpdateUtils();
		utils.updateCertContent();
		renderSuccess();
	}

	// @Clear
	// @Before(TestInterceptor.class)
	// public void updateCity() {
	// try {
	// UpdateUtils utils = new UpdateUtils();
	// utils.start();
	// utils.run();
	// } catch (Exception e) {
	// }
	// renderSuccess();
	// }

	// @Clear
	// @Before(TestInterceptor.class)
	// public void updatecert() throws SQLException {
	// DruidDataSource ds2 = new DruidDataSource();
	// ds2.setUrl("jdbc:mysql://123.56.145.42:3306/superlink");
	// ds2.setUsername("dev");
	// ds2.setPassword("dev");
	//
	// String imgHost = "http://res.superlinkplus.com";
	// SqlRunner runner = SqlRunner.create(ds2);
	//
	// List<LxCertificate> certs = LxCertificate.dao.findAll();
	// for (LxCertificate lxCertificate : certs) {
	// Long certId = lxCertificate.getId();
	// List<Entity> list =
	// runner.findAll(Entity.create("super_course").set("certificate_id",
	// certId));
	// for (Entity course : list) {
	// Long courseId = course.getLong("id");
	// String courseTitle = course.getStr("name");
	// Integer courseSort = course.getInt("sort");
	// Integer courseStatus = course.getInt("status");
	// String content = course.getStr("content");
	//
	// String[] images = content.split(",");
	//
	// String newContent = "";
	// for (String string : images) {
	// String url = imgHost + string;
	// newContent = newContent + url + ";";
	// }
	// String duration = course.getStr("long");
	// // content = content.replace(",", ";");
	// LxCertificateItem certificateItem = new LxCertificateItem();
	// certificateItem.setTitle(courseTitle);
	// certificateItem.setContent(newContent);
	// certificateItem.setDuration(duration);
	// certificateItem.setCertificateId(certId);
	// certificateItem.setSort(courseSort);
	// certificateItem.setStatus(courseStatus);
	// certificateItem.save();
	// Long certificateItemId = certificateItem.getId();
	// List<Entity> exams =
	// runner.findAll(Entity.create("super_exam").set("course_id", courseId));
	// for (Entity exam : exams) {
	// String option = exam.getStr("option");
	// String answer = exam.getStr("answer");
	// String examContent = exam.getStr("content");
	// Integer examSort = course.getInt("sort");
	// Integer examStatus = course.getInt("status");
	// Integer type = course.getInt("question_type");
	// if (type == null) {
	// type = 1;
	// }
	// String[] answers = answer.split(",");
	//
	// ArrayList<DBMap> jsonlist = new ArrayList<DBMap>();
	// String[] options = option.split("\r\n");
	// for (String string : options) {
	// String selectionName = string.split(":")[0];
	// String contents = string.split(":")[1];
	// boolean isAnswer = false;
	// for (String answerName : answers) {
	// if (answerName.equals(selectionName)) {
	// isAnswer = true;
	// }
	// }
	// DBMap map = new DBMap();
	// map.put("title", contents);
	// map.put("isAnswer", isAnswer ? 1 : 0);
	// jsonlist.add(map);
	// }
	// String json = JsonKit.toJson(jsonlist);
	// LxCertificateItemQuestion question = new LxCertificateItemQuestion();
	// question.setCertificateItemId(certificateItemId);
	// question.setQuestion(examContent);
	// question.setType(type);
	// question.setAnswers(json);
	// question.setCertificateItemId(certificateItemId);
	// question.setSort(examSort);
	// question.setStatus(examStatus);
	// question.save();
	// // System.out.println(JsonKit.toJson(list));
	// }
	// }
	// }
	// renderSuccess();
	// }

	@Clear
	@Before(TestInterceptor.class)
	public void updatepolicy() {
		// DruidDataSource ds2 = new DruidDataSource();
		// ds2.setUrl("jdbc:mysql://123.56.145.42:3306/superlink");
		// ds2.setUsername("dev");
		// ds2.setPassword("dev");
		//
		// String imgHost = "http://res.superlinkplus.com/";
		// SqlRunner runner = SqlRunner.create(ds2);
		//
		// String[] lxSchoolIds = { "15", "9", "4", "17", "3", "13", "16", "7",
		// "10", "14", "8" };
		// Long[] schoolIds = { 5L, 3L, 6L, 8L, 4L, 2L, 12L, 9L, 10L, 1L, 7L };
		//
		// for (int idx = 0; idx < 11; idx++) {
		// try {
		// String lxSchoolId = lxSchoolIds[idx];
		// Long schoolId = schoolIds[idx];
		// List<Entity> list =
		// runner.findAll(Entity.create("super_school_news").set("school_id",
		// lxSchoolId));
		// for (Entity entity : list) {
		// if (entity.getInt("status").equals(-1)) {
		// continue;
		// }
		// LxPolicy policy = new LxPolicy();
		// policy.setSchoolId(schoolId);
		// policy.setTitle(entity.getStr("title"));
		// String content = entity.getStr("content");
		// content = content.replace("\n", "<br />");
		// policy.setContent(content);
		// policy.setCover(imgHost + entity.getStr("img"));
		// policy.save();
		// }
		// } catch (SQLException e) {
		// e.printStackTrace();
		// }
		// }
		// List<LxQuestion> items = LxQuestion.dao.findAll();
		// for (LxQuestion lxQuestion : items) {
		// String answer = lxQuestion.getAnswer();
		// answer = answer.replace("\n", "<br />");
		// lxQuestion.setAnswer(answer);
		// lxQuestion.update();
		// }
		renderSuccess("s");
	}

	@Clear
	public void data() {
		String word = getPara("wd", "");
		if (StrKit.isBlank(word)) {
			renderFailure();
			return;
		}
		Integer type = getParaToInt("type");
		if (type == null) {
			renderFailure();
			return;
		}
		Kv kv = Kv.by("word", word).set("type", type);
		SqlPara sqlPara = Db.use("liuxue").getSqlPara("LXFindRawData", kv);
		// System.out.println(sqlPara);
		List<Record> records = Db.use("liuxue").find(sqlPara);
		renderJson(records);
	}

	@Clear
	public void debug() {
		String word = getPara("wd", "");
		if (StrKit.isBlank(word)) {
			renderFailure();
			return;
		}
		Integer type = getParaToInt("type");
		if (type == null) {
			renderFailure();
			return;
		}
		setAttr("word", word);
		setAttr("type", type);
		Kv kv = Kv.by("word", word).set("type", type);
		SqlPara sqlPara = Db.use("liuxue").getSqlPara("LXFindRawData2", kv);
		List<Record> records = Db.use("liuxue").find(sqlPara);
		setAttr("items", JsonKit.toJson(records));
		render("/lx/admin/debug.html");
	}

	private List<Record> getDepartmentList(Long ukId, Integer majorType) {
		Kv kv2 = Kv.create();
		kv2.set("ukSchoolId", ukId);
		kv2.set("majorType", majorType);
		SqlPara sqlPara3 = Db.use("liuxue").getSqlPara("LXFindUKSchoolDepartments", kv2);
		List<Record> departmentList = Db.use("liuxue").find(sqlPara3);
		return departmentList;
	}

	private Ret findSchoolInfo(Long ukSchoolId, Integer major, LxCnSchool cnSchool) {
		Ret ret = Ret.create();

		LxUkSchool ukSchool = LxUkSchool.dao.findById(ukSchoolId);
		ret.set("ukSchoolName", ukSchool.getName());
		ret.set("ukSchoolNameEng", ukSchool.getEngName());
		ret.set("logo", ukSchool.getLogo());
		ret.set("id", ukSchoolId);
		ret.set("departments", getDepartmentList(ukSchoolId, major));

		Kv kv = Kv.by("cnSchoolId", cnSchool.getId());
		kv.set("ukSchoolId", ukSchoolId);
		SqlPara schoolRankPara = lxDb.getSqlPara("LXFindCnSchoolRank", kv);
		// System.out.println(schoolRankPara);
		List<LxSchoolRank> ranks = LxSchoolRank.dao.find(schoolRankPara);
		if (ranks.size() == 0) {
			// 找不到排名,不建议申请
			LogKit.warn("不建议申请排名");
			ret.set("mode", 1);
			return ret;
		}
		// Integer cnSchoolRank = rank.getRank();

		Kv majorKv = Kv.by("ukSchoolId", ukSchoolId);
		majorKv.set("majorType", major);
		majorKv.set("cnSchoolId", cnSchool.getId());
		// System.out.println(majorKv);
		SqlPara sqlPara = lxDb.getSqlPara("LXFindSchoolMajors", majorKv);
		List<Record> majors = lxDb.find(sqlPara);
		// 0.无相关专业,1.不建议申请,2.有相关专业,不跳转,3.有相关专业,跳转
		Integer mode = 0;

		Integer minScore = 100;
		String extra = "";
		if (majors.size() > 0) {
			boolean canFindRank = false;
			boolean isAllNoMore = true;
			for (Record majorInfo : majors) {
				Integer cnSchoolRank = majorInfo.getInt("rank");
				if (cnSchoolRank == null) {
					continue;
				}
				if (majorInfo.getInt("minRank") <= cnSchoolRank && cnSchoolRank <= majorInfo.getInt("maxRank")) {
					canFindRank = true;
					Integer score = majorInfo.getInt("score");
					extra = majorInfo.getStr("extra");
					if (score < minScore) {
						minScore = score;
					}
				}
				Integer isNoMore = majorInfo.getInt("isNoMore");
				if (isAllNoMore) {
					if (isNoMore == null || (isNoMore != null && isNoMore.equals(0))) {
						isAllNoMore = false;
					}
				}
			}
			if (canFindRank) {
				// 查看详细
				// 查找符合排名的学院
				if (isAllNoMore) {
					// 不跳
					mode = 2;
				} else {
					// 跳
					mode = 3;
				}
			} else {
				// 不建议申请
				mode = 1;
			}
		} else {
			// 无相关专业
			mode = 0;
		}
		ret.set("mode", mode);
		ret.set("score", minScore);
		ret.set("majorMinScore", minScore);
		ret.set("majorExtra", extra);
		return ret;
	}

	public void schoolMajors() {
		String cnSchoolId = getPara("cnSchoolId");
		Integer majorType = getParaToInt("majorType");
		Long ukSchoolId = getParaToLong("ukSchoolId");
		Kv kv = Kv.create();
		kv.set("cnSchoolId", cnSchoolId);
		kv.set("majorType", majorType);
		kv.set("ukSchoolId", ukSchoolId);
		SqlPara sqlPara = lxDb.getSqlPara("LXFindUkSchoolMajors", kv);
		List<Record> items = lxDb.find(sqlPara);
		// for (Record record : items) {
		// System.out.println(JsonKit.toJson(record));
		// }
		LxUkSchool ukSchool = LxUkSchool.dao.findById(ukSchoolId);
		DBMap map = new DBMap();
		map.put("school", ukSchool);
		map.put("major", items);
		renderSuccess(map);
	}

	@Before(CacheInterceptor.class)
	@CacheName("30min")
	public void submit2() {
		String cnSchoolId = getPara("cnSchoolId");
		Integer major = getParaToInt("major");
		Long ukSchoolId = getParaToLong("ukSchoolId");

		LxCnSchool cnSchool = LxCnSchool.dao.findById(cnSchoolId);

		ArrayList<Object> arrayList = new ArrayList<>();
		if (ukSchoolId == null) {
			SqlPara sp = db.getSqlPara("LXUkSchoolIds");
			List<Record> ukSchoolIds = db.find(sp);
			// Long[] ukSchoolIds = { 17L, 4L, 7L, 8L, 10L, 6L, 1L, 2L, 5L, 3L, 9L };
			for (Record record : ukSchoolIds) {
				Ret ret = findSchoolInfo(record.getLong("id"), major, cnSchool);
				arrayList.add(ret);
			}
		} else {
			Ret ret = findSchoolInfo(ukSchoolId, major, cnSchool);
			arrayList.add(ret);
		}
		renderSuccess(arrayList);
	}

	public void submit() {
		String cnSchoolId = getPara("cnSchoolId");
		String major = getPara("major");
		String ukSchoolId = getPara("ukSchoolId");

		DBMap map = new DBMap();
		Kv kv = Kv.by("majorType", major);
		if (StrKit.notBlank(ukSchoolId)) {
			kv.set("ukSchoolId", ukSchoolId);
			SqlPara sqlPara = Db.use("liuxue").getSqlPara("LXFindMajorCount", kv);
			Record result = Db.use("liuxue").findFirst(sqlPara);

			long majorCount = result.getLong("result");
			map.put("count", majorCount);
		}

		kv.set("cnSchoolId", cnSchoolId);
		SqlPara sqlPara2 = Db.use("liuxue").getSqlPara("LXFindUKSchools", kv);
		List<Record> records = Db.use("liuxue").find(sqlPara2);

		for (Record record : records) {
			Integer majorType = record.getInt("majorType");
			Long ukId = record.getLong("parentUkSchookId") != null ? record.getLong("parentUkSchookId")
					: record.getLong("id");
			Kv kv2 = Kv.create();
			kv2.set("ukSchoolId", ukId);
			kv2.set("majorType", majorType);
			SqlPara sqlPara3 = Db.use("liuxue").getSqlPara("LXFindUKSchoolDepartments", kv2);
			List<Record> departmentList = Db.use("liuxue").find(sqlPara3);
			record.set("departments", departmentList);
		}
		map.put("list", records);
		renderSuccess(map);
	}

	/**
	 * 首页选择中国的大学
	 */
	public void cnSchools() {
		String keyword = getPara("kw");
		// List<LxCnSchool> list;
		// if (StrKit.isBlank(keyword)) {
		// SqlPara sqlPara = Db.use("liuxue").getSqlPara("LXFindCnSchool");
		// list = LxCnSchool.dao.find(sqlPara);
		// } else {
		// SqlPara sqlPara = Db.use("liuxue").getSqlPara("LXFindCnSchool",
		// Kv.by("keyword", keyword));
		// list = LxCnSchool.dao.find(sqlPara);
		// }
		// renderResult(list);
		String from = "FROM lx_cn_school";
		String totalRowSql = "SELECT count(*) " + from;
		String findSql = null;
		String where = " WHERE lx_cn_school.name LIKE '%" + keyword + "%'";
		String orderBy = " ORDER BY convert(lx_cn_school.`name` using gbk) ASC";
		if (StrKit.isBlank(keyword)) {
			findSql = "SELECT lx_cn_school.* " + from + orderBy;
		} else {
			totalRowSql += where;
			findSql = "SELECT lx_cn_school.* " + from + where + orderBy;
		}
		Page<LxCnSchool> page = LxCnSchool.dao.paginateByFullSql(getPage(), PAGE_SIZE, totalRowSql, findSql);
		renderResult(page);
	}

	/**
	 * 根据英国大学,选择对应专业
	 */
	public void schoolMajor() {
		Long ukSchoolId = getParaToLong("ukSchoolId");
		Long cnSchoolId = getParaToLong("cnSchoolId");
		Integer majorType = getParaToInt("majorType");
		LxUkSchool ukSchool = LxUkSchool.dao.findById(ukSchoolId);
		if (ukSchool == null) {
			renderFailure(404, "invalid id");
			return;
		}
		Kv kv = Kv.create();
		kv.set("ukSchoolId", ukSchool.getSchoolId() != null ? ukSchool.getSchoolId() : ukSchool.getId());
		kv.set("cnSchoolId", cnSchoolId);
		kv.set("majorType", majorType);
		SqlPara sqlPara = Db.use("liuxue").getSqlPara("LXFindUKSchoolMajor", kv);
		List<Record> records = Db.use("liuxue").find(sqlPara);
		// for (Record record : records) {
		// if (record.getInt("isNoMore") != null &&
		// record.getInt("isNoMore").equals(1)) {
		// Kv kv2 = Kv.create();
		// kv2.set("ukSchoolId", ukSchoolId);
		// kv2.set("majorType", majorType);
		// SqlPara sqlPara2 =
		// Db.use("liuxue").getSqlPara("LXFindUKSchoolDepartments", kv2);
		// List<Record> departmentList = Db.use("liuxue").find(sqlPara2);
		// record.set("departments", departmentList);
		// }
		// }

		DBMap map = new DBMap();
		map.put("school", ukSchool);
		map.put("major", records);
		renderSuccess(map);
	}

	public void ukSchools() {
		// String cnSchoolId = getPara("cnSchoolId");
		// SqlPara sqlPara = Db.use("liuxue").getSqlPara("FindUkSchoolByCnId",
		// Kv.by("cnSchoolId", cnSchoolId));
		// List<LxUkSchool> list = LxUkSchool.dao.find(sqlPara);

		String keyword = getPara("kw");
		List<LxUkSchool> list;
		if (StrKit.isBlank(keyword)) {
			SqlPara sqlPara = Db.use("liuxue").getSqlPara("LXFindUkSchool");
			list = LxUkSchool.dao.paginate(1, PAGE_SIZE, sqlPara).getList();
		} else {
			SqlPara sqlPara = Db.use("liuxue").getSqlPara("LXFindUkSchool", Kv.by("keyword", keyword));
			list = LxUkSchool.dao.paginate(1, PAGE_SIZE, sqlPara).getList();
		}
		renderResult(list);
	}

	/**
	 * 录取标准查询统计
	 */
	public void countSearch() {
		LxStatistic stat = new LxStatistic();
		stat.setType(5);
		stat.save();
		renderSuccess();
	}

}
